package com.hue.concurrent.day03;

/**
 * 多线程下使用while循环判断来防止线程虚假唤醒
 */
public class Demo03 {
    private static Object room = new Object();
    //有没有烟
    private static boolean flag1 = false;
    //有没有外卖
    private static boolean flag2 = false;

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (room) {
                System.out.println("小南准备干活");
                while (!flag1) {
                    System.out.println("没有烟，歇会");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("有烟，开始干活");
            }
        }).start();

        new Thread(() -> {
            synchronized (room) {
                System.out.println("小女准备干活");
                while (!flag2) {
                    System.out.println("没有外卖，歇会");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("有外卖，开始干活");
            }
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (room){
            //送外卖
            System.out.println("外卖到了");
            flag2 = true;
            room.notifyAll();
        }
    }
}
